package com.cindata

import grails.gorm.transactions.Transactional
import groovy.transform.CompileStatic
import groovy.transform.TypeChecked

@Transactional
class WorkflowInstanceUserService
{

    static scope = "singleton"

    def initWorkflowInstanceUser(WorkflowInstanceStage workflowInstanceStage, WorkflowStage workflowStage)
    {
        def workflowInstanceUser

        def workflowUsers = WorkflowUser.findAll("from WorkflowUser where stage.id = ${workflowStage?.id}")
        workflowUsers?.each {
            def users = UserRole.findAllByRole(it?.role)*.user
            users.each { user ->
                workflowInstanceUser = WorkflowInstanceUser.find("from WorkflowInstanceUser where user.id = ${user?.id} and stage.id = ${workflowInstanceStage?.id} and authority.id = ${it?.authority?.id} ")
                if (!workflowInstanceUser)
                {
                    workflowInstanceUser = new WorkflowInstanceUser()
                    workflowInstanceUser.stage = workflowInstanceStage
                    workflowInstanceUser.user = user
                    workflowInstanceUser.authority = it?.authority
                    if (workflowInstanceUser.validate())
                    {
                        workflowInstanceUser.save flush: true
                    }
                    else
                    {
                        println workflowInstanceUser.errors
                    }
                }
            }
        }
    }
}
